<template>
  <div>
    <n-card style="height: 550px">
      <div class="canvas-wrapper">
        <canvas
            v-if="paintImagUrl"
            ref="canvasRef"
            :width="imageWidth"
            :height="imageHeight"
            style="background-color:  rgba(255, 0, 0, 0.1);"
        >
        </canvas>
        <img
            v-if="paintImagUrl"
            ref="img2img_imgRef"
            :height="imageHeight"
            :width="imageWidth"
            :src="fileFunction.getViewFilePathByUserFileId(paintImagUrl)"
        />
      </div>
    </n-card>
    <n-space style="margin-top:20px" justify="space-between">
      <n-scrollbar x-scrollable style="max-height: 150px">
        <div style="white-space: nowrap;">
          <n-image
              v-for="pic in props.screenshotList"
              preview-disabled
              :lazy="true"
              :width="70"
              size="small"
              @click="loadImage(pic.userFileId)"
              :class="{ 'selected': pic == paintImagUrl }"
              style="margin-left: 10px;"
              :src=fileFunction.getViewFilePathByUserFileId(pic.userFileId)
          />
        </div>
      </n-scrollbar>
      <n-space>
        <n-tag type="info" size="large"> 您选择了{{ cropRect.length }}块区域</n-tag>
        <n-button type="primary" @click="loadImage(paintImagUrl)">清空区域</n-button>
      </n-space>
    </n-space>

    <n-space v-if="props.mode==='batch'">
      <n-form-item label="开始序号" label-placement="left">
        <n-input-number v-model:value="startNum" :show-button="false"></n-input-number>
      </n-form-item>
    </n-space>

    <n-grid :x-gap="5" :cols="2">
      <n-grid-item>
        <n-button block type="primary" @click="removeWaterMarker" :loading="removeWaterMarkerLoading">模糊水印
        </n-button>
      </n-grid-item>
      <n-grid-item>
        <n-button block type="info" @click="cleanUpWaterMarker" :loading="removeWaterMarkerLoading">去除水印</n-button>
      </n-grid-item>
    </n-grid>


    <n-modal
        v-model:show="progressModal"
        class="custom-card"
        style="width: 500px"
        preset="card"
        :mask-closable="false"
        title="图片去除水印"
        size="huge"
        :bordered="false"
    >
      <n-h4>一共有{{ totalNum }}图片去除水印</n-h4>
      <n-space justify="space-around">
        <n-statistic label="当前进度:" :value="finishNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ totalNum }}
          </template>
        </n-statistic>
      </n-space>
      <n-progress
          type="line"
          :percentage=" finishNum === 0? 0 : Math.round(finishNum/totalNum *100) "
          :height="30"
          :border-radius="5"
          :fill-border-radius="0"
      />
    </n-modal>
  </div>

</template>

<script setup lang="ts">
import {defineEmits, ref} from "vue";
//@ts-ignore
import fileFunction from "@/libs/globalFunction/file";
import {videoController} from "@/api/controller/video/videoController.api";
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
import {storyController} from "@/api/story/story.api";

const canvasRef = ref(null)
const ctx = ref(null)
const image = ref(null);
const fixedHeight = 500;
const cropRect = ref([])
const isDrawing = ref(false)
const paintImagUrl = ref('')
const removeWaterMarkerLoading = ref(false)



const totalNum = ref(0)
const finishNum = ref(0)
const failureNum = ref(0)
const progressModal = ref(false)


const props = defineProps({
  screenshotList: {
    type: Array,
    default: [],
    required: true
  },
  story: {
    type: Object,
    default: {}
  },
  storyBoardId: {
    type: String,
  },
  mode: {
    type: String,
    required: true
  }
})

const startNum = ref(0)

const imageWidth = ref(500)
const imageHeight = ref(500)



const scaleFactor = ref(1)

const loadImage = (imageSrc: string) => {
  paintImagUrl.value = imageSrc
  image.value = new Image()
  image.value.src = fileFunction.getViewFilePathByUserFileId(imageSrc)
  image.value.onload = () => {
    ctx.value = canvasRef.value.getContext('2d')
    if(image.value.height > fixedHeight) {
      scaleFactor.value = fixedHeight / image.value.height;
      imageWidth.value = image.value.width * (fixedHeight / image.value.height)
      imageHeight.value = fixedHeight
    }else {
      imageWidth.value = image.value.width
      imageHeight.value = image.value.height
    }
    ctx.value.clearRect(0, 0, imageWidth.value, imageHeight.value)
    initCrop()
  }
  cropRect.value = []
}

const drawImage = () => {
  if (imageHeight.value > fixedHeight) {
    scaleFactor.value = fixedHeight / imageHeight.value;
    const newWidth = imageWidth.value * scaleFactor.value;
    const newHeight = fixedHeight;
    canvasRef.value.width = newWidth
    canvasRef.value.height = newHeight
    ctx.value.drawImage(image.value, 0, 0, newWidth, newHeight);
  } else {
    canvasRef.value.width = imageWidth.value
    canvasRef.value.height = imageHeight.value
    ctx.value.drawImage(image.value, 0, 0, imageWidth.value, imageHeight.value);
  }
}

const initCrop = () => {
  let startX, startY;
  canvasRef.value.addEventListener("mousedown", (e: any) => {
    startX = e.offsetX;
    startY = e.offsetY;
    isDrawing.value = true;
  });

  canvasRef.value.addEventListener("mouseup", (e: any) => {
    if (isDrawing.value) {
      isDrawing.value = false;
      let endX = e.offsetX;
      let endY = e.offsetY;

      console.log('scaleFactor', scaleFactor.value)
      if (scaleFactor.value) {
        endX = endX / scaleFactor.value
        endY = endY / scaleFactor.value
        startX = startX / scaleFactor.value
        startY = startY / scaleFactor.value
      }
      cropRect.value.push(
          {
            x: Math.min(startX, endX),
            y: Math.min(startY, endY),
            width: Math.abs(startX - endX),
            height: Math.abs(startY - endY),
          }
      )
    }
  });

  canvasRef.value.addEventListener("mousemove", (e: any) => {
    if (isDrawing.value) {
      ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
      // drawImage()
      drawRect(startX, startY, e.offsetX - startX, e.offsetY - startY);
    }
  });
};


const drawRect = (x, y, width, height) => {
  if (cropRect.value.length > 0) {
    cropRect.value.forEach((item) => {
      ctx.value.strokeStyle = "white";
      ctx.value.fillStyle = 'white'
      ctx.value.lineWidth = 0;
      if (scaleFactor.value) {
        ctx.value.fillRect(item.x * scaleFactor.value, item.y * scaleFactor.value, item.width * scaleFactor.value, item.height * scaleFactor.value);
      }
    });
  }
  ctx.value.strokeStyle = "white";
  ctx.value.fillStyle = 'white'
  ctx.value.lineWidth = 0;
  ctx.value.fillRect(x, y, width, height);
};


const emit = defineEmits()


const removeWaterMarker = () => {
  let area: string[] = []
  cropRect.value.forEach((item) => {
    area.push(JSON.stringify(item))
  });
  if (props.mode === 'batch') {
    const param = {
      storyId: props.story.id,
      areas: area,
      userFileId: props.story.userFileId,
      startNum: startNum.value
    }
    removeWaterMarkerLoading.value = true
    videoController.removeWaterMarkerTask(param, 5 * 60 * 1000, removeWaterMarkerLoading, progressModal, totalNum, finishNum).then(res => {
      emit('loadSuccessEvent')
    }).finally(() => {
      removeWaterMarkerLoading.value = false
    })
  } else {
    const param = {
      storyBoardId: props.storyBoardId,
      areas: area,
      userFileId: props.story.userFileId
    }
    removeWaterMarkerLoading.value = true
    videoController.imageRemoveWaterMarkerForPic(param).then(res => {
      if (res.code === 200) {
        emit('loadSuccessEvent')
      }
    }).finally(() => {
      removeWaterMarkerLoading.value = false
    })
  }
}


const cleanUpWaterMarker = async () => {
  const response = await getBase64Mask()
  if (props.mode === 'batch') {

    storyController.getStoryBoardList(props.story.id).then(async res => {
      // totalNum.value = res.data.length
      console.log(res)
      if (res.code == 200) {
        // 开始去水印
        const boardList = res.data.records
        removeWaterMarkerLoading.value = true
        totalNum.value = boardList.length
        finishNum.value = 0
        progressModal.value = true
        for (const storyBoard of boardList) {
          const param = {
            storyBoardId: storyBoard.id,
            area: response,
            exampleFileId: storyBoard.examplePic,
            videoFileId: props.story.userFileId
          }
          await storyBoardController.cleanUpWaterMarker(param).then(res => {
            if (res.code == 200) {
              finishNum.value = finishNum.value + 1
            }
          }).catch(err => {
            failureNum.value = failureNum.value + 1
          })
        }
        emit('loadSuccessEvent')
        progressModal.value = false
        removeWaterMarkerLoading.value = false
      }
    })
  } else {
    removeWaterMarkerLoading.value = true
    const param = {
      storyBoardId: props.storyBoardId,
      area: response,
      exampleFileId: props.screenshotList[0].userFileId,
      videoFileId: props.story.userFileId
    }
    storyBoardController.cleanUpWaterMarker(param).then(res => {
      if (res.code === 200) {
        console.log('res', res)
        emit('loadSuccessEvent')
      }
    }).finally(() => {
      removeWaterMarkerLoading.value = false
    })
  }
}


const getBase64Mask = async () => {
  // const imageData = ctx.value.getImageData(0, 0, imageWidth.value , imageHeight.value)
  // // 将修改后的图像数据导出为图片格式
  // const exportCanvas = document.createElement('canvas')
  // exportCanvas.width = imageWidth.value
  // exportCanvas.height = imageHeight.value
  // const exportCtx = exportCanvas.getContext('2d')
  // exportCtx.putImageData(imageData, 0, 0);
  // // exportCtx?.scale(imageWidth / scaleFactor.value, imageHeight / scaleFactor.value)
  // exportCtx.scale(1 / scaleFactor.value, 1 / scaleFactor.value);
  // mask放大到和原图一致
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = canvasRef.value.toDataURL()
    image.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = imageWidth.value/scaleFactor.value
      canvas.height = imageHeight.value/scaleFactor.value
      const ctx_canvas = canvas.getContext('2d')
      ctx_canvas.drawImage(image, 0, 0, canvas.width, canvas.height);
      resolve(canvas.toDataURL())
    }
  })
}



</script>
